package com.milkshopbackend.milkshop.Service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.milkshopbackend.milkshop.Service.CartService;
import com.milkshopbackend.milkshop.Service.ProductService;
import com.milkshopbackend.milkshop.entity.Cart;
import com.milkshopbackend.milkshop.entity.CartDTO;
import com.milkshopbackend.milkshop.entity.Product;
import com.milkshopbackend.milkshop.mapper.CartMapper;
import com.milkshopbackend.milkshop.mapper.ProductMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductMapper productMapper;

    @Override
    @Transactional
    public void addToCart(Long userId, CartDTO cartDTO) {
        Product product = productMapper.selectById(cartDTO.getProductId());
        // 判断商品是否存在
        if (product == null) {
            log.error("商品不存在");
            throw new RuntimeException("商品不存在");
        }
        // 判断商品是否在售
        if (!product.getStatus()) {
            log.error("商品已下架");
            throw new RuntimeException("商品已下架");
        }
        // 判断商品规格库存
        int stock = 0;
        if ("large".equals(cartDTO.getSpecType())) {
            stock = product.getLargeStock() != null ? product.getLargeStock() : 0;
        } else if ("medium".equals(cartDTO.getSpecType())) {
            stock = product.getMediumStock() != null ? product.getMediumStock() : 0;
        } else {
            throw new RuntimeException("规格类型错误");
        }
        if (stock < cartDTO.getQuantity()) {
            throw new RuntimeException("商品库存不足");
        }
        // 判断购物车中是否已存在该商品和规格
        Cart existingCart = this.lambdaQuery()
                .eq(Cart::getUserId, userId)
                .eq(Cart::getProductId, cartDTO.getProductId())
                .eq(Cart::getSpecType, cartDTO.getSpecType())
                .one();
        if (existingCart != null) {
            existingCart.setQuantity(existingCart.getQuantity() + cartDTO.getQuantity());
            this.updateById(existingCart);
        } else {
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setProductId(cartDTO.getProductId());
            cart.setSpecType(cartDTO.getSpecType());
            cart.setQuantity(cartDTO.getQuantity());
            this.save(cart);
        }
    }

    @Override
    public List<Cart> getCartByUserId(Long userId) {
        return this.lambdaQuery()
                .eq(Cart::getUserId, userId)
                .orderByDesc(Cart::getCreateTime)
                .list();
    }

    @Override
    @Transactional
    public void updateCartItem(Long userId, Long cartId, Integer quantity) {
        Cart cart = this.getById(cartId);
        if (cart == null || !cart.getUserId().equals(userId)) {
            throw new RuntimeException("购物车商品不存在");
        }

        Product product = productService.getProduct(cart.getProductId());
        // 判断商品是否在售
        if (!product.getStatus()) {
            log.error("商品已下架");
            throw new RuntimeException("商品已下架");
        }

        // 判断商品库存是否充足
        if (product.getStock() < quantity) {
            throw new RuntimeException("商品库存不足");
        }
        cart.setQuantity(quantity);
        this.updateById(cart);
    }

    @Override
    @Transactional
    public void removeCartItem(Long userId, Long cartId) {
        Cart cart = this.getById(cartId);
        if (cart == null || !cart.getUserId().equals(userId)) {
            throw new RuntimeException("购物车商品不存在");
        }
        this.removeById(cartId);
    }

    @Override
    @Transactional
    public void clearCart(Long userId) {
        this.lambdaUpdate()
                .eq(Cart::getUserId, userId)
                .remove();
    }
}
